package main

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)

var clientk *mongo.Client

func initkDB() {
	//设置客户端
	co := options.Client().ApplyURI("mongodb://127.0.0.1:27017")
	//连接
	var err error //error 默认为nil
	c, err := mongo.Connect(context.TODO(), co)
	if err != nil {
		log.Fatal(err)
	}
	//检查连接
	err = c.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Connected to MongoDB!")
	clientk = c
}

// 更新
func update() {
	initkDB()
	ctx := context.TODO()
	defer clientk.Disconnect(ctx)
	c := clientk.Database("go_db").Collection("student")

	update := bson.D{{
		"$set",
		bson.D{
			{"name", "big tom"},
			{"Age", 25},
		},
	}}

	ur, err := c.UpdateMany(ctx, bson.D{{"name", "tom"}}, update)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("ur.ModifiedCount:%v\n", ur.ModifiedCount) //修改了几条记录
}
func main() {
	update()
}
